<?php
 /**
   * This program is free software; you can redistribute it and/or
   * modify it under the terms of the GNU General Public License
   * as published by the Free Software Foundation; either version 2
   * of the License, or any later version.
   *
   * This program is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   * GNU General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
   * along with this program; if not, write to the Free Software
   * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
   *
   * ----------------------------------------------------------------------
   * NimWiki - designer centric wiki
   *
   * @author Nicolas Myers <myers.nicolas@gmail.com>
   * @copyright 2007 Nicolas Myers
   * @version 0.9.0
   * @link
   * ----------------------------------------------------------------------
   * HELPERS.PHP
   *
   * collection of functions used in php templates
   * ----------------------------------------------------------------------
   */
   
   
   /**
    * Returns the requested page in html
    * if given, returns a specific "part" (portion of code between [part:name][/part] tags)
    * @param   string  $pagename
    * @param   string  $part 
    * @return  string  xhtml produced
    * @see WikiRenderer.lib.php
    */
    function wiki2html($pagename, $part = "") 
    {
        $filename = getFilename($pagename);
        $raw = file_get_contents($filename);
        $wkr = new WikiRenderer();
        // if part is defined
        if ($part != "") {
            $tagStart = 0;
            $cleanraw = "";
            $tagOpen = "[part:$part]";
            $tagClose = "[/part]";
            while ($tagStart = strpos($raw, $tagOpen, $tagStart)) {
                //tag is starting and ending
                if ($tagStop = strpos($raw, $tagClose, $tagStart)) {
                    $cleanraw .= substr($raw, $tagStart + strlen($tagOpen), $tagStop - $tagStart - strlen($tagOpen));
                    $tagStart = $tagStop;
                } else {
                    //no ending tag => pbm!
                    return "err";
                }
            }
            return $wkr->render(str_replace("\r\n", "\n", $cleanraw));
        } else {
            //renders everything but "part" blocs
            $offset = 0;
            $tagStart = 0;
            $cleanraw = "";
            $tagOpen = "[part";
            $tagClose = "[/part]";
            while ($tagStart = strpos($raw, $tagOpen, $offset)) {
                //tag is starting and ending
                if ($tagStop = strpos($raw, $tagClose, $tagStart)) {
                    $cleanraw .= substr($raw, $offset, $tagStart - $offset);
                    $offset = $tagStop + strlen($tagClose);
                } else {
                    //no ending tag => pbm!
                    return "err";
                }
            }
            if($offset != 0)$cleanraw .= substr($raw, $offset);
            if($cleanraw == "")$cleanraw = $raw;
            return $wkr->render(str_replace("\r\n", "\n", $cleanraw));
        }
    }

   /**
    * Returns html links to switch to a different available language
    * @param   string  $pagename
    * @return  string  xhtml produced
    */
    function langSwitcher($pagename)
    {
        global $cfg;
        foreach ($cfg['lang_names'] as $key => $val) {
            if ($key == $cfg['lang']) {
                return "$val<br />";
            } else {
                $url = makeUrl($pagename);
                return "<a href=\"$url&lang=$key\" >$val</a><br />";
            }
        }
    }

   /**
    * Returns a correct url
    * @param   string  $pagename
    * @return  string  url
    */
    function makeUrl($pagename="")
    {
        global $cfg;
        $pagename = str_replace('#', '/', $pagename);
        return $cfg['frontctrl'] . '?' . $cfg['wiki_get'] . '=' . $pagename;
    }
    
   /**
    * Returns an html SELECT with all the editable pages in the wiki
    * @param   string  $pagename
    * @return  string  xhtml produced
    */
    function selectAllPages($pagename)
    {
        global $cfg;
        $privatePages = array("AllPages", "RecentChanges", "FindPage");
        // list all existent pages
        $handle = opendir($cfg['data_dir'] . $cfg['lang'] . "/");
        while ($newfile = basename(readdir($handle), ".dat")) {
            if ((strpos($newfile, '.') === false) and (!in_array($newfile, $privatePages)))
                $allpages[] = $newfile;
        }
        sort($allpages);
        $html = '';
        foreach ($allpages as $page) {
            $select = ($pagename==$page) ? "selected" : "";
            $html .= "<option value =\"index.php?{$cfg['wiki_get']}=$page&do=edit\" $select >" . unNormalizeStr(str_replace("#", "/", $page)) . "</option>\n";
        }
        $html .= '';
        return $html;
    }

   /**
    * Normalize a string => lowercase, remove accents, spaces and invalid chars
    * used to produce filename and links
    * @param   string  $rawtag
    * @return  string  normalize string
    */
    function normalizeStr($rawStr)
    {
        $accent     = utf8_decode(" .ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿ");
        $noaccent   = utf8_decode("__aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyyby");
        $normStr    = strtr(trim(html_entity_decode(utf8_decode($rawStr), ENT_NOQUOTES)), $accent, $noaccent);
        $validChars = 'a-zA-Z0-9-_\/';
        $normStr    = preg_replace("/[^$validChars]/", "", $normStr);
        return strtolower($normStr);
    }

    /**
    * Beautifier to reverse the normalize function (see above)
    * capitalize and remove underscores
    * @param   string  $normStr
    * @return  string  transformed string
    */
    function unNormalizeStr($normStr)
    {
      return ucfirst(str_replace('_', ' ', $normStr));
    }

    /**
    * Returns the new width and height of an image (width x height)
    * fitting in a box (widthMax x heightMax)
    * @param   int    $width
    * @param   int    $height
    * @param   int    $widthMax
    * @param   int    $heightMax
    * @return  array  ($newWidth,$newHeight)
    */
    function getNewBoxSize($width,$height,$widthMax,$heightMax)
    {
        $ratioImage = $width / $height;
        $ratioCadre = $widthMax / $heightMax;
        if ($ratioImage > $ratioCadre) {
            //source image is wider than the target box
            $newWidth = $widthMax;
            $newHeight = ceil($widthMax / $ratioImage);
        } else {
            //source image is higher than the target box
            $newHeight = $heightMax;
            $newWidth = ceil($heightMax * $ratioImage);
        }
        return array ($newWidth,$newHeight);
    }

?>
